<template>
  <div>
    <!-- 面包屑 -->
    <div class="mb-6 text-sm text-gray-500 flex items-center">
      <router-link to="/dashboard" class="hover:text-gray-700">控制台</router-link>
      <i class="fas fa-chevron-right mx-2"></i>
      <span class="text-gray-900 font-medium">线路管理</span>
    </div>

    <!-- 标题与操作 -->
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">线路管理</h1>
        <p class="text-gray-600 mt-1">管理管道线路信息、里程桩设置和线路维护</p>
      </div>
      <div class="flex space-x-3">
        <button 
          @click="handleAdd"
          class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-plus"></i>
          <span>新增线路</span>
        </button>
        <button 
          v-if="selectedLines.length > 0"
          @click="handleBatchDelete"
          class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-trash"></i>
          <span>批量删除 ({{ selectedLines.length }})</span>
        </button>
        <button 
          @click="handleExport"
          class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-file-export"></i>
          <span>导出数据</span>
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">总线路数</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.totalLines }}</p>
          </div>
          <div class="bg-blue-100 p-3 rounded-lg">
            <i class="fas fa-route text-blue-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">总里程</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.totalLength }}</p>
            <p class="text-xs text-gray-500">公里</p>
          </div>
          <div class="bg-green-100 p-3 rounded-lg">
            <i class="fas fa-road text-green-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">正常运行</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.normalCount }}</p>
          </div>
          <div class="bg-green-100 p-3 rounded-lg">
            <i class="fas fa-check-circle text-green-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">维护中</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.maintenanceCount }}</p>
          </div>
          <div class="bg-yellow-100 p-3 rounded-lg">
            <i class="fas fa-wrench text-yellow-600 text-xl"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <div class="relative">
            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            <input 
              v-model="searchForm.keyword"
              type="text" 
              placeholder="搜索线路名称或编号..." 
              class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @keyup.enter="handleSearch"
            >
          </div>
          <select 
            v-model="searchForm.status"
            class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            @change="handleSearch"
          >
            <option value="">全部状态</option>
            <option v-for="option in statusOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <select 
            v-model="searchForm.region"
            class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            @change="handleSearch"
          >
            <option value="">全部区域</option>
            <option v-for="option in regionOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
          <button 
            @click="handleSearch"
            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            <i class="fas fa-search mr-1"></i>搜索
          </button>
          <button 
            @click="handleReset"
            class="bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200 transition-colors"
          >
            <i class="fas fa-undo mr-1"></i>重置
          </button>
        </div>
        <button 
          @click="handleRefresh"
          class="text-blue-600 hover:text-blue-800 flex items-center space-x-1"
        >
          <i class="fas fa-sync-alt"></i>
          <span>刷新</span>
        </button>
      </div>
    </div>

    <!-- 线路列表表格 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
      <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
        <h3 class="text-lg font-semibold text-gray-900">线路列表</h3>
        <div v-if="loading" class="text-sm text-gray-500">
          <i class="fas fa-spinner fa-spin mr-1"></i>加载中...
        </div>
      </div>
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300"
                  :checked="selectAll"
                  @change="handleSelectAll($event.target.checked)"
                >
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">线路编号</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">线路名称</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">起点</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">终点</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">长度</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">区域</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最近巡检</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="item in lineList" :key="item.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300"
                  :checked="selectedLines.includes(item.id)"
                  @change="handleSelect($event.target.checked, item)"
                >
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ item.lineCode }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.lineName }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.startPoint }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.endPoint }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.lengthKm }} km</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ regionText[item.region] }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(item.status)" class="inline-flex px-2 py-1 text-xs font-semibold rounded-full">
                  {{ statusText[item.status] }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.lastInspection }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center space-x-2">
                  <button 
                    @click="handleView(item)"
                    class="text-blue-600 hover:text-blue-800"
                    title="查看详情"
                  >
                    <i class="fas fa-eye"></i>
                  </button>
                  <button 
                    @click="handleEdit(item)"
                    class="text-green-600 hover:text-green-800"
                    title="编辑"
                  >
                    <i class="fas fa-edit"></i>
                  </button>
                  <button 
                    @click="handleDelete(item)"
                    class="text-red-600 hover:text-red-800"
                    title="删除"
                  >
                    <i class="fas fa-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
            <tr v-if="lineList.length === 0 && !loading">
              <td colspan="10" class="px-6 py-8 text-center text-gray-500">
                <i class="fas fa-inbox text-4xl mb-2"></i>
                <p>暂无数据</p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示 {{ (pagination.pageNum - 1) * pagination.pageSize + 1 }}-{{ Math.min(pagination.pageNum * pagination.pageSize, pagination.total) }} 条，共 {{ pagination.total }} 条记录
          </div>
          <div class="flex items-center space-x-2">
            <button 
              @click="handlePageChange(pagination.pageNum - 1)"
              :disabled="pagination.pageNum <= 1"
              class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              上一页
            </button>
            <button 
              v-for="page in Math.ceil(pagination.total / pagination.pageSize)"
              :key="page"
              @click="handlePageChange(page)"
              :class="[
                'px-3 py-1 text-sm rounded',
                page === pagination.pageNum 
                  ? 'bg-blue-600 text-white' 
                  : 'border border-gray-300 hover:bg-gray-50'
              ]"
            >
              {{ page }}
            </button>
            <button 
              @click="handlePageChange(pagination.pageNum + 1)"
              :disabled="pagination.pageNum >= Math.ceil(pagination.total / pagination.pageSize)"
              class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑/查看弹窗 -->
    <div v-if="dialogVisible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-900">{{ dialogTitle }}</h3>
          <button 
            @click="dialogVisible = false"
            class="text-gray-400 hover:text-gray-600"
          >
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>
        
        <div class="p-6">
          <form @submit.prevent="handleSave" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">线路编号 *</label>
                <input 
                  v-model="formData.lineCode"
                  type="text"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入线路编号"
                >
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">线路名称 *</label>
                <input 
                  v-model="formData.lineName"
                  type="text"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入线路名称"
                >
              </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">起点 *</label>
                <input 
                  v-model="formData.startPoint"
                  type="text"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入起点"
                >
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">终点 *</label>
                <input 
                  v-model="formData.endPoint"
                  type="text"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入终点"
                >
              </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">线路长度(km) *</label>
                <input 
                  v-model="formData.length"
                  type="number"
                  step="0.1"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入线路长度"
                >
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">区域 *</label>
                <select 
                  v-model="formData.region"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择区域</option>
                  <option v-for="option in regionOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <select 
                  v-model="formData.status"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option v-for="option in statusOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>
              <div v-if="dialogMode === 'view'">
                <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                <input 
                  v-model="formData.createTime"
                  type="text"
                  disabled
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                >
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">描述</label>
              <textarea 
                v-model="formData.description"
                :disabled="dialogMode === 'view'"
                rows="3"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入线路描述"
              ></textarea>
            </div>
            
            <div v-if="dialogMode === 'view'">
              <label class="block text-sm font-medium text-gray-700 mb-1">最近巡检</label>
              <input 
                v-model="formData.lastInspection"
                type="text"
                disabled
                class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
              >
            </div>
          </form>
        </div>
        
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
          <button 
            @click="dialogVisible = false"
            class="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
          >
            取消
          </button>
          <button 
            v-if="dialogMode !== 'view'"
            @click="handleSave"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            {{ dialogMode === 'add' ? '新增' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { lineAPI } from '@/api/modules'

/**
 * 响应式数据
 */
// 线路列表数据
const lineList = ref([])
const loading = ref(false)
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = ref({
  keyword: '',
  status: '',
  region: ''
})

// 统计卡片数据
const statistics = ref({
  totalLines: 0,
  totalLength: 0,
  normalCount: 0,
  maintenanceCount: 0
})

// 选中的线路
const selectedLines = ref([])
const selectAll = ref(false)

// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('add') // add, edit, view

// 表单数据
const formData = ref({
  id: null,
  lineCode: '',
  lineName: '',
  startPoint: '',
  endPoint: '',
  length: '',
  region: '',
  status: 'normal',
  description: '',
  createTime: '',
  lastInspection: ''
})

// 表单验证规则
const formRules = ref({
  lineCode: [
    { required: true, message: '请输入线路编号', trigger: 'blur' },
    { min: 3, max: 20, message: '线路编号长度在3到20个字符', trigger: 'blur' }
  ],
  lineName: [
    { required: true, message: '请输入线路名称', trigger: 'blur' },
    { min: 2, max: 50, message: '线路名称长度在2到50个字符', trigger: 'blur' }
  ],
  startPoint: [
    { required: true, message: '请输入起点', trigger: 'blur' }
  ],
  endPoint: [
    { required: true, message: '请输入终点', trigger: 'blur' }
  ],
  length: [
    { required: true, message: '请输入线路长度', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择区域', trigger: 'change' }
  ]
})

// 状态选项
const statusOptions = [
  { label: '正常运行', value: 'normal' },
  { label: '维护中', value: 'maintenance' },
  { label: '停用', value: 'disabled' }
]

// 区域选项
const regionOptions = [
  { label: '东区', value: 'east' },
  { label: '西区', value: 'west' },
  { label: '南区', value: 'south' },
  { label: '北区', value: 'north' }
]

/**
 * 计算属性
 */
const statusText = computed(() => {
  const statusMap = {
    normal: '正常运行',
    maintenance: '维护中',
    disabled: '停用'
  }
  return statusMap
})

const regionText = computed(() => {
  const regionMap = {
    east: '东区',
    west: '西区',
    south: '南区',
    north: '北区'
  }
  return regionMap
})

/**
 * 模拟数据
 */
const mockLineData = [
  {
    id: 1,
    lineCode: 'XL001',
    lineName: '东区主干管道',
    startPoint: '泵站A',
    endPoint: '储罐B',
    length: 15.2,
    region: 'east',
    status: 'normal',
    description: '东区主要输油管道，负责原油输送',
    createTime: '2024-01-01 10:00:00',
    lastInspection: '2024-01-15'
  },
  {
    id: 2,
    lineCode: 'XL002',
    lineName: '西区支线管道',
    startPoint: '储罐C',
    endPoint: '泵站D',
    length: 8.5,
    region: 'west',
    status: 'maintenance',
    description: '西区支线管道，定期维护中',
    createTime: '2024-01-02 14:30:00',
    lastInspection: '2024-01-10'
  },
  {
    id: 3,
    lineCode: 'XL003',
    lineName: '南区连接管道',
    startPoint: '泵站E',
    endPoint: '储罐F',
    length: 12.8,
    region: 'south',
    status: 'normal',
    description: '南区连接管道，正常运行',
    createTime: '2024-01-03 09:15:00',
    lastInspection: '2024-01-12'
  },
  {
    id: 4,
    lineCode: 'XL004',
    lineName: '北区备用管道',
    startPoint: '储罐G',
    endPoint: '泵站H',
    length: 6.3,
    region: 'north',
    status: 'disabled',
    description: '北区备用管道，暂时停用',
    createTime: '2024-01-04 16:45:00',
    lastInspection: '2023-12-20'
  }
]

/**
 * 获取线路列表
 */
const loadLineList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      keyword: searchForm.value.keyword || undefined,
      status: searchForm.value.status || undefined,
      region: searchForm.value.region || undefined
    }
    
    const response = await lineAPI.getLines(params)
    
    if (response.code === 0) {
      const data = response.data
      lineList.value = data.records || []
      
      // 更新分页信息
      pagination.value.total = data.total || 0
      pagination.value.pages = data.pages || 0
    } else {
      throw new Error(response.message || '获取线路列表失败')
    }
    
  } catch (error) {
    console.error('加载线路列表失败:', error)
    ElMessage.error('加载线路列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 更新统计数据
 */
const updateStatistics = async () => {
  try {
    const response = await lineAPI.getLineStatistics()
    
    if (response.code === 0) {
      const data = response.data
      statistics.value = {
        totalLines: data.totalLines || 0,
        totalLength: data.totalLength || 0,
        normalCount: data.normalCount || 0,
        maintenanceCount: data.maintenanceCount || 0
      }
    } else {
      console.error('获取统计数据失败:', response.message)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

/**
 * 搜索功能
 */
const handleSearch = () => {
  pagination.value.pageNum = 1
  loadLineList()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  searchForm.value = {
    keyword: '',
    status: '',
    region: ''
  }
  pagination.value.pageNum = 1
  loadLineList()
}

/**
 * 刷新数据
 */
const handleRefresh = () => {
  loadLineList()
}

/**
 * 分页处理
 */
const handlePageChange = (page) => {
  pagination.value.pageNum = page
  loadLineList()
}

/**
 * 全选/取消全选
 */
const handleSelectAll = (checked) => {
  selectAll.value = checked
  if (checked) {
    selectedLines.value = lineList.value.map(item => item.id)
  } else {
    selectedLines.value = []
  }
}

/**
 * 单个选择
 */
const handleSelect = (checked, item) => {
  if (checked) {
    selectedLines.value.push(item.id)
  } else {
    const index = selectedLines.value.indexOf(item.id)
    if (index > -1) {
      selectedLines.value.splice(index, 1)
    }
  }
  
  // 更新全选状态
  selectAll.value = selectedLines.value.length === lineList.value.length
}

/**
 * 新增线路
 */
const handleAdd = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '新增线路'
  formData.value = {
    id: null,
    lineCode: '',
    lineName: '',
    startPoint: '',
    endPoint: '',
    length: '',
    region: '',
    status: 'normal',
    description: '',
    createTime: '',
    lastInspection: ''
  }
  dialogVisible.value = true
}

/**
 * 编辑线路
 */
const handleEdit = (item) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑线路'
  formData.value = { 
    ...item,
    length: item.lengthKm // 将lengthKm映射到length字段
  }
  dialogVisible.value = true
}

/**
 * 查看线路详情
 */
const handleView = (item) => {
  dialogMode.value = 'view'
  dialogTitle.value = '线路详情'
  formData.value = { 
    ...item,
    length: item.lengthKm // 将lengthKm映射到length字段
  }
  dialogVisible.value = true
}

/**
 * 删除线路
 */
const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除线路"${item.lineName}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await lineAPI.deleteLine(item.id)
    
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadLineList()
      updateStatistics()
    } else {
      throw new Error(response.message || '删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除线路失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  if (selectedLines.value.length === 0) {
    ElMessage.warning('请选择要删除的线路')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedLines.value.length} 条线路吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await lineAPI.batchDeleteLines(selectedLines.value)
    
    if (response.code === 0) {
      ElMessage.success('批量删除成功')
      selectedLines.value = []
      selectAll.value = false
      loadLineList()
      updateStatistics()
    } else {
      throw new Error(response.message || '批量删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除线路失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

/**
 * 保存线路
 */
const handleSave = async () => {
  try {
    // 表单验证
    if (!formData.value.lineCode.trim()) {
      ElMessage.warning('请输入线路编号')
      return
    }
    if (!formData.value.lineName.trim()) {
      ElMessage.warning('请输入线路名称')
      return
    }
    if (!formData.value.startPoint.trim()) {
      ElMessage.warning('请输入起点')
      return
    }
    if (!formData.value.endPoint.trim()) {
      ElMessage.warning('请输入终点')
      return
    }
    if (!formData.value.length || isNaN(formData.value.length)) {
      ElMessage.warning('请输入有效的线路长度')
      return
    }
    if (!formData.value.region) {
      ElMessage.warning('请选择区域')
      return
    }
    
    let response
    if (dialogMode.value === 'add') {
      response = await lineAPI.createLine(formData.value)
    } else {
      response = await lineAPI.updateLine(formData.value.id, formData.value)
    }
    
    if (response.code === 0) {
      ElMessage.success(dialogMode.value === 'add' ? '新增线路成功' : '编辑线路成功')
      dialogVisible.value = false
      loadLineList()
      updateStatistics()
    } else {
      throw new Error(response.message || '保存失败')
    }
    
  } catch (error) {
    console.error('保存线路失败:', error)
    ElMessage.error('保存失败')
  }
}

/**
 * 导出数据
 */
const handleExport = async () => {
  try {
    ElMessage.info('正在导出数据...')
    
    // 模拟导出API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

/**
 * 获取状态样式类
 */
const getStatusClass = (status) => {
  const classes = {
    normal: 'bg-green-100 text-green-800',
    maintenance: 'bg-yellow-100 text-yellow-800',
    disabled: 'bg-gray-100 text-gray-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

/**
 * 组件挂载时加载数据
 */
onMounted(() => {
  loadLineList()
  updateStatistics()
})
</script>

<style scoped>
.toolbar { margin-bottom: 12px; display: flex; gap: 8px; }
.grid { display: grid; grid-template-columns: 420px 1fr; gap: 16px; }
.card { background: #fff; border: 1px solid #eee; padding: 16px; border-radius: 6px; }
</style>
